package me.obstsalat.guildera;

import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.inventory.ItemStack;

public class g_chat {
	
	private static guildera plugin;
	
	g_chat(guildera pl) {
		plugin = pl;
	}
	
	public boolean onPlayerChat(PlayerChatEvent chat) {
		Player ply = chat.getPlayer();
		String msg = chat.getMessage();
		if(!plugin.checkViableWorld(ply.getWorld())) {
			return false;
		}
		if(msg.startsWith(".g ")) {
				chat.setCancelled(true);
				for(guild g : plugin.guilds) {
					if(g.hasMember(ply.getName())) {
						String msg2 = msg.replace(".g ", "");
						g.announce("[" + g.getName() + "] " + ply.getName() + ": " + msg2);
					}
				}
		} else if(msg.startsWith(".guild create ")) {
			chat.setCancelled(true);
			if(plugin.restricted_founders.contains(ply.getName())) {
				ply.sendMessage("You can only create a new guild once a day.");
			} else {
				boolean hasguild = false;
				for(guild g : plugin.guilds) {
					if(g.hasMember(ply.getName())) {
						hasguild = true;
					}
				}
				if(!hasguild) {
					boolean name_used = false;
					boolean distance = true;
					boolean distance2 = true;
					boolean distance3 = true;
					String n = "Fairy Tail";
					n = msg.split(" ")[2];
					for(Location2d l : plugin.rA) {
						long dx = ply.getLocation().getBlockX() - l.getX();
						long dz = ply.getLocation().getBlockZ() - l.getZ();
						if((dx*dx)+(dz*dz) < (160*160)) {
							distance2 = false;
						}
					}
					for(guild g : plugin.guilds) {
						if(g.getName().equalsIgnoreCase(n)) {
							name_used = true;
						}
						for(Location2d l2d : g.getAreaList()) {
							long dx = l2d.getX() - ply.getLocation().getBlockX();
							long dz = l2d.getZ() - ply.getLocation().getBlockZ();
							if((dx*dx)+(dz*dz) <= (80*80)) {
								distance = false;
							}
						}
					}
					if(true) {
						long dx = plugin.overworld.getSpawnLocation().getBlockX() - ply.getLocation().getBlockX();
						long dz = plugin.overworld.getSpawnLocation().getBlockZ() - ply.getLocation().getBlockZ();
						if((dx*dx)+(dz*dz) < (plugin.config.getInt("spawn_guild_protection")*plugin.config.getInt("spawn_guild_protection"))) {
							distance3 = false;
						}
					}
					if(!name_used && distance && distance2 && distance3 && ply.getLocation().getWorld() == plugin.overworld) {
						if(!ply.getLocation().getWorld().getName().equals(plugin.overworld.getName())) {
							ply.sendMessage("You can't create a guild in this world.");
							return true;
						}
						guild ge = new guild( plugin, n, ply.getLocation(),ply.getName());
						plugin.guilds.add(ge);
						ge.save(plugin);
						plugin.restricted_founders.add(ply.getName());
						for(Player plx : plugin.getServer().getOnlinePlayers()) {
							plx.sendMessage(ply.getName() + " founded " + ge.getName() + " recently!");
						}
						plugin.logger.info("[" + plugin.getDescription().getName() + "]" + ply.getName() + " founded " + ge.getName() + " recently!");
					} else {
						if(name_used) {
							ply.sendMessage("The guild " + n + " exists already!");
						} else if(!distance) {
							ply.sendMessage("You are too near too another guild to found a new one!");
						} else if(!distance2) {
							ply.sendMessage("You are too near too a dungeon to found a new guild!");
						} else if(ply.getLocation().getWorld() != plugin.overworld) {
							ply.sendMessage("You can only found a guild in the overworld!");
						} else if(!distance3) {
							ply.sendMessage("You are too near to the spawn to found a new guild!");
						} else {
							ply.sendMessage("You made a mistake. Please try it again.");
						}
					}
					
				} else {
					ply.sendMessage("You can only create a new guild when you are not a member of a guild.");
				}
			}
		} else if(msg.startsWith(".guild leave")) {
			chat.setCancelled(true);
			for(int i = 0; i < plugin.guilds.size(); i++) {
				guild g = plugin.guilds.get(i);
				if(g.hasMember(ply.getName())) {
					GuildMember gm = g.getMember(ply.getName());
					if(gm.getRank() != 3 || g.getNumMember() == 1) {
						g.removeMember(ply.getName());
						for(Player plx : plugin.getServer().getOnlinePlayers()) {
							plx.sendMessage(ply.getName() + " left " + g.getName() + ".");
							if(g.getNumMember() <= 0) {
								plugin.removeGuild(g);
							}
						}
					} else {
						ply.sendMessage("You need to announce a new leader before you can leave the guild.");
					}
				}
			}
		} else if(msg.startsWith(".guild save")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					g.save(plugin);
					ply.sendMessage("Guild saved!");
				}
			}
		} else if(msg.startsWith(".guild info")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					ply.sendMessage(g.getName() + ":");
					ply.sendMessage(" -Level: " + g.getLevel());
					ply.sendMessage(" -Experience to next Level: " + g.getEpToNextlevel());
					long max_npcs = g.getArea() / 64;
					long current_npcs = 0;
					for(Entity ent : plugin.overworld.getEntities()) {
						if(ent.getType() == EntityType.VILLAGER && g.isInGuild(ent.getLocation())) {
							current_npcs++;
						}
					}
					ply.sendMessage(" -Area: " + g.getArea());
					ply.sendMessage(" -Villagers: " + current_npcs + "/" + max_npcs);
					ply.sendMessage("To see the members, type in .guild members.");
				}
			}
		} else if(msg.startsWith(".help")) {
			chat.setCancelled(true);
			ply.sendMessage("Commands:");
			boolean has_guild = false;
			int rank = 0;
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					has_guild = true;
					rank = g.getMember(ply.getName()).getRank();
				}
			}
			if(!has_guild) {
				ply.sendMessage(".guild create [name] - Used to create a new guild at the position of the player.");
			} else {
				ply.sendMessage(".guild info - Shows infos about your guild.");
				ply.sendMessage(".guild members - Shows member of your guild.");
				ply.sendMessage(".guild save - Saves the guildprogress.");
				ply.sendMessage(".guild leave - This way you leave your guild.");
				ply.sendMessage(".guild return - Teleports you to your guild.");
				ply.sendMessage(".g [message] - Guild-only chat.");
				if(rank==3) {
					ply.sendMessage(".guild trust [name] - Trusts a guild member. These ones can invite and kick other guild members.");
					ply.sendMessage(".guild untrust [name] - Untrusts a guild member.");
					ply.sendMessage(".guild leader [name] - Appoints a new leader. Old leader will become trusted member.");
					
				}
				if(rank>=2) {
					ply.sendMessage(".guild invite [name] - Invites a player to the guild.");
					ply.sendMessage(".guild kick [name] - Kicks this member out of the guild.");
					ply.sendMessage(".guild expand - You buy a 8*8 square area for your guild for 1 gold block.");
					ply.sendMessage(".guild setreturn - Sets the location of the return point to your current location.");
				}
			}
			ply.sendMessage(".guild list - Shows a list of all guilds of this server.");
			ply.sendMessage(".guild in - Shows the name of the guild that owns the area you are in.");
			ply.sendMessage(".guild getinfo [name] - Displays members and level of a guild.");
			
			ply.sendMessage(".help - Shows this commandtable.");
		} else if(msg.startsWith(".guild expand")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					if(g.getMember(ply.getName()).getRank() >= 2) {
						Block target = ply.getTargetBlock(null, 128);
						if(target.getTypeId() == 41) {
							int x1 = Math.max(ply.getLocation().getBlockX(), target.getX()); //greater
							int x2 = Math.min(ply.getLocation().getBlockX(), target.getX()); //smaller
							int z1 = Math.max(ply.getLocation().getBlockZ(), target.getZ()); //greater
							int z2 = Math.min(ply.getLocation().getBlockZ(), target.getZ()); //smaller
							int exp_size = plugin.config.getInt("expand_size");
							if((x1 - x2) != (exp_size - 1) || (z1 - z2) != (exp_size - 1)) {
								ply.sendMessage("There has to be a " + exp_size + "*" + exp_size + " square area between you and the gold block you look at.");
							} else {
								boolean nexttoguild = false;
								if(g.isInGuild(new Location2d(x1 + 1,z1))) {
									nexttoguild = true;
								} else if(g.isInGuild(new Location2d(x1 + 1,z2))) {
									nexttoguild = true;
								} else if(g.isInGuild(new Location2d(x2 - 1,z1))) {
									nexttoguild = true;
								} else if(g.isInGuild(new Location2d(x2 - 1,z2))) {
									nexttoguild = true;
								} else if(g.isInGuild(new Location2d(x1,z1 + 1))) {
									nexttoguild = true;
								} else if(g.isInGuild(new Location2d(x2,z1 + 1))) {
									nexttoguild = true;
								} else if(g.isInGuild(new Location2d(x1,z2 - 1))) {
									nexttoguild = true;
								} else if(g.isInGuild(new Location2d(x2,z2 - 1))) {
									nexttoguild = true;
								}
								if(!ply.getLocation().getWorld().getName().equals(plugin.overworld.getName())) {
									nexttoguild = false;
								}
								if(nexttoguild) {
									int cash = exp_size*exp_size;
									for(int dx = x2; dx <= x1; dx++) {
										for(int dz = z2; dz <= z1; dz++) {
											boolean is_restricted = false;
											for(Location2d l : plugin.rA) {
												if(l.equal(new Location2d(dx,dz))) {
													ply.sendMessage("A field of your new bought area is too near to a dungeon.");
													is_restricted = true;
												}
											}
											if(!is_restricted) {
												for(guild ge : plugin.guilds) {
													if(ge.isInGuild(new Location2d(dx,dz)) && !ge.getName().equals(g.getName())) {
														is_restricted = true;
													}
												}
												if(!is_restricted && !g.isInGuild(new Location2d(dx,dz))) {
													cash--;
													g.addArea(new Location2d(dx,dz));
													int y = 1 + worldLib.getSurface(dx, dz, worldLib.SURFACE_HIGHEST, worldLib.SURFACE2_IGNORELIQUID);
													worldLib.spawnBlock(dx, y, dz, 13);
													for(int i = 0; i < plugin.guilds.size(); i++) {
														guild ge = plugin.guilds.get(i);
														if(!ge.getName().equals(g.getName())) {
															boolean disband = false;
															boolean check = false;
															if(ge.isInGuild(new Location2d(dx + 1,dz))) {
																check = true;
															} else if(ge.isInGuild(new Location2d(dx - 1,dz))) {
																check = true;
															} else if(ge.isInGuild(new Location2d(dx,dz + 1))) {
																check = true;
															} else if(ge.isInGuild(new Location2d(dx,dz - 1))) {
																check = true;
															}
															if(check) {
																disband = true;
																for(Location2d l2d : ge.getAreaList()) {
																	if(!ge.isInGuild(new Location2d(l2d.getX() + 1,l2d.getZ())) && !g.isInGuild(new Location2d(l2d.getX() + 1,l2d.getZ()))) {
																		disband = false;
																	} else if(!ge.isInGuild(new Location2d(l2d.getX() - 1,l2d.getZ())) && !g.isInGuild(new Location2d(l2d.getX() - 1,l2d.getZ()))) {
																		disband = false;
																	} else if(!ge.isInGuild(new Location2d(l2d.getX(),l2d.getZ() + 1)) && !g.isInGuild(new Location2d(l2d.getX(),l2d.getZ() + 1))) {
																		disband = false;
																	} else if(!ge.isInGuild(new Location2d(l2d.getX(),l2d.getZ() - 1)) && !g.isInGuild(new Location2d(l2d.getX(),l2d.getZ() - 1))) {
																		disband = false;
																	}
																}
																if(disband) {
																	for(Player plx : plugin.getServer().getOnlinePlayers()) {
																		plx.sendMessage(g.getName() + " defeated " + ge.getName() + ". " + ge.getName() + " will be disbanded.");
																	}
																	plugin.removeGuild(ge);
																}
															}
														}
													}
												} else if(is_restricted) {
													ply.sendMessage("A field of your new bought area already belongs to a guild.");
												}
											}
										}
									}
									if(cash != (exp_size*exp_size)) {
										target.setTypeId(0);
									}
									if(cash != (exp_size) && (cash/exp_size) > 0) {
										for(int i = 1; i <= (cash/exp_size); i++) {
											plugin.overworld.dropItem(target.getLocation(), new ItemStack(266));
										}
									}
									g.announce(ply.getName() + " expanded the guild area by " + ((exp_size*exp_size) - cash) + " fields.");
								} else {
									ply.sendMessage("The " + exp_size + "*" + exp_size + "square has to be next to your guild area.");
								}
							}
						} else {
							ply.sendMessage("You need to look at a gold block to perform this action.");
						}
					} else {
						ply.sendMessage("You need to be the leader or a trusted member to use this command.");
					}
				}
			}
		} else if(msg.startsWith(".guild return")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					Location2d l2d = new Location2d(ply.getLocation());
					boolean allow = true;
					for(Location2d l : plugin.rA) {
						if(l.equal(l2d)) {
							allow = false;
						}
					}
					for(guild ge : plugin.guilds) {
						if(!ge.getName().equals(g.getName()) && ge.isInGuild(l2d)) {
							allow = false;
						}
					}
					if(allow) {
						ply.teleport(g.getTeleport());
					} else {
						ply.sendMessage("You can't use this command in enemy guilds or dungeons.");
					}
				}
			}
		} else if(msg.startsWith(".guild setreturn")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					if(g.getMember(ply.getName()).getRank() >= 2 && g.isInGuild(ply.getLocation()) && ply.getLocation().getWorld().getName().equals(plugin.overworld.getName())) {
						g.setTeleport(ply.getLocation());
						g.announce(ply.getName() + " has made a new teleport point.");
					} else {
						ply.sendMessage("You need to be a trusted Member and in the guild to perform this action.");
					}
				}
			}
		} else if(msg.startsWith(".guild leader ")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					GuildMember leader = g.getMember(ply.getName());
					if(leader.getRank() == 3) {
						if(msg.split(" ")[2].equals(ply.getName())) {
							ply.sendMessage("You are already leading the guild?!");
						} else {
							Player pl = plugin.getServer().getPlayer(msg.split(" ")[2]);
							if(pl instanceof Player) {
								GuildMember trusted = g.getMember(pl.getName());
								if(trusted != null) {
									g.setRank(trusted, 3);
									g.setRank(leader, 2);
									pl.sendMessage("The guildleader made you to the new guildleader!");
									ply.sendMessage("You are no longer the guildleader. You remain as trusted guildmember.");
									g.announce(ply.getName() + " made " + pl.getName() + " to the new guildleader.");
								} else {
									ply.sendMessage("There is no guildmember with the name " + msg.split(" ")[2] + "!");
								}
							} else {
								plugin.logger.info("[" + plugin.getDescription().getName() + "] Something went wrong in g_chat:onChat() (Note: .guild leader command). Please grab a developer if this problems occurs more often.");
							}
						}
					} else {
						ply.sendMessage("Only the guildleader can perform this action.");
					}
				}
			}
		} else if(msg.startsWith(".guild kick ")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {			
					GuildMember leader = g.getMember(ply.getName());
					if(leader.getRank() == 3) {
						Player pl = plugin.getServer().getPlayer(msg.split(" ")[2]);
						if(ply.equals(pl)) {
							ply.sendMessage("U mad bro?");
						} else {
							if(pl instanceof Player) {
								GuildMember trusted = g.getMember(pl.getName());
								if(trusted != null) {
									g.removeMember(trusted.getName());
									pl.sendMessage("The guildleader has made you leaving the guild!");
									g.announce(pl.getName() + " had to leave the guild!");
								} else {
									ply.sendMessage("There is no guildmember with the name " + msg.split(" ")[2] + "!");
								}
							}
						}
					} else {
						ply.sendMessage("Only the guildleader can perform this action.");
					}
				}
			}
		} else if(msg.startsWith(".guild trust ")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					GuildMember leader = g.getMember(ply.getName());
					if(leader.getRank() == 3) {
						Player pl = plugin.getServer().getPlayer(msg.split(" ")[2]);
						if(ply.equals(pl)) {
							ply.sendMessage("Cant get enough ehh?");
						} else {
							if(pl instanceof Player) {
								GuildMember trusted = g.getMember(pl.getName());
								if(trusted != null) {
									g.setRank(trusted, 2);
									pl.sendMessage("The guildleader has faith in you and you are now a trusted guildmember!");
									g.announce("The guildleader has faith in " + pl.getName() + ".");
								} else {
									ply.sendMessage("There is no guildmember with the name " + msg.split(" ")[2] + "!");
								}
							}
						}
					} else {
						ply.sendMessage("Only the guildleader can perform this action.");
					}
				}
			}
		} else if(msg.startsWith(".guild untrust ")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					GuildMember leader = g.getMember(ply.getName());
					if(leader.getRank() == 3) {
						Player pl = plugin.getServer().getPlayer(msg.split(" ")[2]);
						if(ply.equals(pl)) {
							ply.sendMessage("Are you fucking kidding me?");
						} else {
							if(pl instanceof Player) {
								GuildMember trusted = g.getMember(pl.getName());
								if(trusted != null) {
									g.setRank(trusted, 1);
									pl.sendMessage("The guildleader has lost his faith in you. You are not a trusted guildmember anymore!");
									g.announce("The guildleader has lost his faith in " + pl.getName() + ".");
								} else {
									ply.sendMessage("There is no guildmember with the name " + msg.split(" ")[2] + "!");
								}
							}
						}
					} else {
						ply.sendMessage("Only the guildleader can perform this action.");
					}
				}
			}
		} else if(msg.startsWith(".disband ")) {
			chat.setCancelled(true);
			String msg2 = msg.split(" ")[1];
			if(ply.isOp()) {
				for(int i = 0; i < plugin.guilds.size(); i++) {
					if(plugin.guilds.get(i).getName().equalsIgnoreCase(msg2)) {
						plugin.removeGuild(plugin.guilds.get(i));
					}
				}
			} else {
				ply.sendMessage("You don't have the permission to use this command.");
			}
		} else if(msg.startsWith(".guild getinfo ")) {
			chat.setCancelled(true);
			String msg2 = msg.split(" ")[2];
			for(guild g : plugin.guilds) {
				if(g.getName().equalsIgnoreCase(msg2)) {
					ply.sendMessage(msg2 + ", Level " + g.getLevel());
					ply.sendMessage("Area: " + g.getArea());
					for(GuildMember gm : g.getMembers()) {
						if(gm.getRank() == 3) {
							ply.sendMessage(gm.getName() + ", Guildleader");
						} else if(gm.getRank() == 2) {
							ply.sendMessage(gm.getName() + ", trusted Member");
						} else {
							ply.sendMessage(gm.getName() + ", Member");
						}
					}
				}
			}
		} else if(msg.startsWith(".guild members")) {
			chat.setCancelled(true);
			for(guild g : plugin.guilds) {
				if(g.hasMember(ply.getName())) {
					ply.sendMessage(g.getName() + " members:");
					for(GuildMember gm : g.getMembers()) {
						if(gm.getRank() == 3) {
							ply.sendMessage(" " + gm.getName() + ", Guildleader");
						} else if(gm.getRank() == 2) {
							ply.sendMessage(" " + gm.getName() + ", trusted Guildmember");
						} else {
							ply.sendMessage(" " + gm.getName() + ", Guildmember");
						}
					}
				}
			}
		} else if(msg.startsWith(".guild list")) {
			chat.setCancelled(true);
			ply.sendMessage("The following guilds exist on this server:");
			for(guild g : plugin.guilds) {
				ply.sendMessage(" - " + g.getName() + ", Level " + g.getLevel() + ", " + g.getNumMember() + " Member");
			}
		} else if(msg.startsWith(".guild invite ")) {
			chat.setCancelled(true);
			Player pl = plugin.getServer().getPlayer(msg.split(" ")[2]);
			if(pl != null) {
				guild ply_guild = null;
				boolean pl_hasguild = false;
				GuildMember gm = null;
				for(guild g : plugin.guilds) {
					if(g.hasMember(ply.getName())) {
						ply_guild = g;
						gm = g.getMember(ply.getName());
					}
					if(g.hasMember(pl.getName())) {
						pl_hasguild = true;
					}
				}
				if(ply_guild != null) {
					if(pl_hasguild) {
						ply.sendMessage(pl.getName() + " is already in a guild.");
					} else if(gm.getRank() <= 1){
						ply.sendMessage("You need to be atleast a trusted guildmember to invite new members.");
					} else {
						if(ply_guild.isInGuild(pl.getLocation())) {
							ply_guild.addMember(pl.getName());
							for(Player plx : plugin.getServer().getOnlinePlayers()) {
								plx.sendMessage(pl.getName() + " joined " + ply_guild.getName() + ".");
							}
							plugin.logger.info("[" + plugin.getDescription().getName() + "] " + pl.getName() + " joined " + ply_guild.getName() + ".");
						} else {
							ply.sendMessage(pl.getName() + " has to be in the guilds capital to be invited!");
						}
					}
				} else {
					ply.sendMessage("You have to be in a guild to invite other people into your guild.");
				}
			} else {
				ply.sendMessage("There is no player named " + msg.split(" ")[2] + ".");
			}
		} else if(msg.startsWith(".guild in")) {
			chat.setCancelled(true);
			String str = null;
			for(guild g : plugin.guilds) {
				if(g.isInGuild(ply.getLocation())) {
					str = g.getName();
				}
			}
			if(str == null) {
				ply.sendMessage("This area does not belong to a guild.");
			} else {
				ply.sendMessage("This area belongs to " + str + ".");
			}
		}
		return chat.isCancelled();
	}

}
